
package com.eltonkent.ui;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

import com.eltonkent.R;
import com.eltonkent.db.FolderListTable;
import com.eltonkent.db.SafeEntryTable;
import com.eltonkent.ui.adapters.DialogFolderListAdapter;
import com.eltonkent.ui.adapters.SafeEntryListAdapter;
import com.eltonkent.ui.containers.DialogFolderListContainer;
import com.eltonkent.ui.containers.SafeEntryContainer;
import com.eltonkent.ui.containers.TemplateFieldContainer;

public class SafeEntriesActivity extends ParentActivity
{
	private ListView list;
	private String currentFolderName;
	private static final int DLG_TEMPLATE_TYPE = 11;
	private static final int DLG_TEMPLATE_NAME = 15;

	private static final int ACTIVITY_GET_TEMPLATE = 15;
	private static final int ACTIVITY_SAVE_TEMPLATE = 19;
	private static final int ACTIVITY_VIEW_TEMPLATE = 25;

	private ArrayList<TemplateFieldContainer> entryFieldList;
	private String templateIcon;

	private AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
		{
			container = (SafeEntryContainer) list.getAdapter().getItem(position);
			Log.e("UI", "List item clicked at position " + position);
			Intent intent = new Intent(getApplicationContext(), ViewSafeEntryActivity.class);
			intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_UID, container.getEntryUID());
			intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_ICON, container.getIconID());
			intent.putExtra(ApplicationConstants.EXTRA_FOLDER_NAME, currentFolderName);
			intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_NAME, container.getSafeEntryName());
			startActivityForResult(intent, ACTIVITY_VIEW_TEMPLATE);
		}
	};

	private SafeEntryContainer container;

	private String template;

	private Dialog getDeleteDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_deletefolder, R.string.delete_entry);
		Button[] okCancel = getOKCancelButtons(dialog);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				dialog.dismiss();
			}
		});
		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				SafeEntryTable table = new SafeEntryTable(getApplicationContext());
				table.deleteEntry(container.getEntryUID(), currentFolderName);
				refreshList();
				dialog.dismiss();
			}
		});
		return dialog;
	}

	private Dialog getMoveDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_listdisplay, R.string.folder_types);
		final ListView list = (ListView) dialog.findViewById(R.id.detailList);
		list.setDividerHeight(0);
		list.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				DialogFolderListContainer folderInfo = (DialogFolderListContainer) list.getAdapter()
						.getItem(arg2);
				SafeEntryTable table = new SafeEntryTable(getApplicationContext());
				table.changeEntryFolder(container.getEntryUID(), currentFolderName, folderInfo
						.getFolderName());
				refreshList();
				dialog.dismiss();
			}
		});
		return dialog;
	}

	private Dialog getTemplateNameDialog()
	{
		final Dialog templateNameDlg = getCustomDialog(R.layout.dialog_templatename,
				R.string.template_name_title);
		Button[] okCancel = getOKCancelButtons(templateNameDlg);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		final TextView errorText = (TextView) templateNameDlg.findViewById(R.id.errorText);
		final EditText templateText = (EditText) templateNameDlg.findViewById(R.id.templateName);
		templateText.requestFocus();
		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Editable templateName = templateText.getText();
				/* empty template name */
				if(templateName.toString().equals(""))
				{
					errorText.setText(R.string.template_name_error);
					errorText.setVisibility(View.VISIBLE);
				} else
				{
					errorText.setVisibility(View.GONE);
					Intent intent = new Intent(getApplicationContext(), EditTemplateActivity.class);
					intent.putParcelableArrayListExtra(ApplicationConstants.EXTRA_FIELD_CONTAINER,
							entryFieldList);
					intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_ICON, templateIcon);
					intent.putExtra(ApplicationConstants.EXTRA_FOLDER_NAME, currentFolderName);
					intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_NAME, templateName.toString());
					intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE, template);
					intent.putExtra(ApplicationConstants.EXTRA_TEMPLATE_ISNEW, true);
					startActivityForResult(intent, ACTIVITY_SAVE_TEMPLATE);
					templateText.setText("");
					templateNameDlg.dismiss();
				}
			}
		});
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				errorText.setText("");
				errorText.setVisibility(View.GONE);
				templateNameDlg.dismiss();

			}
		});
		return templateNameDlg;
	}

	private Dialog getTemplateTypeDialog()
	{
		final Dialog templateList = getCustomDialog(R.layout.dialog_templatetype, R.string.addentry);
		Button btnPredefined = (Button) templateList.findViewById(R.id.predefined);
		Button btnCustom = (Button) templateList.findViewById(R.id.custom);
		btnPredefined.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(getApplicationContext(), TemplateListActivity.class);
				startActivityForResult(intent, ACTIVITY_GET_TEMPLATE);
				templateList.dismiss();
			}
		});

		btnCustom.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(getApplicationContext(), CustomTemplateListActivity.class);
				startActivityForResult(intent, ACTIVITY_GET_TEMPLATE);
				templateList.dismiss();
			}
		});
		return templateList;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode != RESULT_CANCELED)
		{
			switch(requestCode)
			{
				case ACTIVITY_GET_TEMPLATE:
					Log.d("UI", "Template selected");
					entryFieldList = data
							.getParcelableArrayListExtra(ApplicationConstants.EXTRA_FIELD_CONTAINER);
					templateIcon = data.getStringExtra(ApplicationConstants.EXTRA_TEMPLATE_ICON);
					template = data.getStringExtra(ApplicationConstants.EXTRA_TEMPLATE);
					Log.d("UI", "The number of fields are " + entryFieldList.size());
					Log.d("UI", "Template icon" + templateIcon);
					showDialog(DLG_TEMPLATE_NAME);
					break;
				case ACTIVITY_SAVE_TEMPLATE:
				case ACTIVITY_VIEW_TEMPLATE:
					refreshList();
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem menuItem)
	{
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) menuItem.getMenuInfo();
		container = (SafeEntryContainer) list.getAdapter().getItem(menuInfo.position);
		switch(menuItem.getItemId())
		{
			case R.id.mnu_DeleteEntry:
				showDialog(ApplicationConstants.DIALOG_DELETE);
				break;
			case R.id.mnu_MoveToFolder:
				showDialog(ApplicationConstants.DIALOG_MOVE);
				break;

		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.foldercontentscontextmenu, menu);
	}

	@Override
	protected final Dialog onCreateDialog(int id)
	{
		switch(id)
		{
			case DLG_TEMPLATE_TYPE:
				return getTemplateTypeDialog();
			case DLG_TEMPLATE_NAME:
				return getTemplateNameDialog();
			case ApplicationConstants.DIALOG_DELETE:
				return getDeleteDialog();
			case ApplicationConstants.DIALOG_MOVE:
				return getMoveDialog();
			default:
				return super.onCreateDialog(id);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.foldercontentsmenu, menu);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			Log.d("UI", "Back key pressed on folder contents");
			removeTextOnlyFromPath(currentFolderName);
			finish();

			return true;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
			/* Add new folder */
			case R.id.mnu_AddEntry:
				showDialog(DLG_TEMPLATE_TYPE);
				return true;
		}
		return false;
	}

	@Override
	protected void onPrepareDialog(int id, final Dialog dialog)
	{
		switch(id)
		{
			case ApplicationConstants.DIALOG_DELETE:
				TextView tv = (TextView) dialog.findViewById(R.id.dialogText);
				tv.setText(getResources().getString(R.string.delete) + " " + container.getSafeEntryName()
						+ "?");
				break;
			case ApplicationConstants.DIALOG_MOVE:
				ListView list = (ListView) dialog.findViewById(R.id.detailList);
				FolderListTable table = new FolderListTable(getApplicationContext());
				DialogFolderListAdapter adapter = new DialogFolderListAdapter(getApplicationContext(),
						R.layout.listview_icon_singleline, table.getFoldersOnly(currentFolderName));
				list.setAdapter(adapter);
		}
	}

	@Override
	public Object[] onRetainNonConfigurationInstance()
	{
		/* field list, template icon, template,container */
		return new Object[]
		{ entryFieldList, templateIcon, template, container };
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void populateUI()
	{
		addToPath(currentFolderName);
		refreshList();
		Object[] instanceData = (Object[]) this.getLastNonConfigurationInstance();
		if(instanceData != null)
		{
			entryFieldList = (ArrayList<TemplateFieldContainer>) instanceData[0];
			templateIcon = (String) instanceData[1];
			template = (String) instanceData[2];
			container = (SafeEntryContainer) instanceData[3];
		}
	}

	private void refreshList()
	{
		SafeEntryTable table = new SafeEntryTable(getApplicationContext());
		SafeEntryContainer[] entries = table.getSafeEntries(currentFolderName);
		TextView textView = (TextView) findViewById(R.id.noEntries);
		if(entries.length == 0)
		{
			textView.setVisibility(View.VISIBLE);
			textView.setText(R.string.noentries_safe_entries);
		} else
		{
			textView.setVisibility(View.GONE);
		}

		list.setAdapter(new SafeEntryListAdapter(getApplicationPreferences(), getApplicationContext(),
				R.layout.listview_icon_dblline_template, entries));
		setStatusText(entries.length + " " + getResources().getString(R.string.total_items));
	}

	@Override
	protected void setupUI(Bundle savedInstance)
	{
		setContentView(R.layout.activity_genericlist);
		list = (ListView) findViewById(R.id.folderList);
		list.setDividerHeight(0);
		list.setOnItemClickListener(listClickListener);
		registerForContextMenu(list);
		Intent intent = getIntent();
		currentFolderName = intent.getStringExtra(ApplicationConstants.EXTRA_FOLDER_NAME);
		// currentFolderType = intent.getIntExtra(
		// ActivityConstants.EXTRA_FOLDER_ID, 0);
		Log.d("UI", "FOLDER NAME SELECTED->" + currentFolderName);
		// Log.d("UI", "FOLDER TYPE SELECTED->" + currentFolderType);
	}
}
